package club.zhcs.capture.biz.dept.impl;

import java.util.List;

import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import com.dgj.utils.db.SqlActuator;
import com.dgj.utils.entries.Result;
import com.dgj.utils.web.pager.Pager;

import club.zhcs.capture.bean.dept.Contract;
import club.zhcs.capture.biz.dept.IContractService;
import club.zhcs.capture.dao.dept.IContractDao;
import static club.zhcs.capture.vo.Consts.SystemValues.*;

@IocBean
public class ContractService implements IContractService {

	@Inject
	IContractDao contractDao;

	@Override
	public Result add(Contract contract) {
		return null == contractDao.save(contract) ? Result.fail("添加合同失败") : Result.success().addData("contract", contract);
	}

	@Override
	public Pager<Record> listByPage(int page) {
		Sql sql = Sqls
				.create("SELECT c.*,p.p_name,u.u_real_name FROM gj_contract c LEFT JOIN gj_project p ON c.c_project_id = p.id LEFT JOIN gj_user u ON c.c_principal_id = u.id LIMIT @pageStart,@pageSize");
		sql.params().set("pageStart", (page - 1) * PAGESIZE);
		sql.params().set("pageSize", PAGESIZE);
		Pager<Record> pager = new Pager<Record>(PAGESIZE, page);
		pager.setEntities(SqlActuator.runReport(sql, contractDao.getDao()));
		pager.setCount(contractDao.countAll());
		return pager;
	}

	@Override
	public boolean delete(int id) {
		return contractDao.delById(id);
	}

	@Override
	public Record getAllInfo(int id) {
		Sql sql = Sqls
				.create("SELECT c.*,p.p_name,p.id AS p_id,u.u_real_name,u.id AS u_id FROM gj_contract c LEFT JOIN gj_project p ON c.c_project_id = p.id LEFT JOIN gj_user u ON c.c_principal_id = u.id WHERE c.id = @id");
		sql.params().set("id", id);
		List<Record> records = SqlActuator.runReport(sql, contractDao.getDao());
		return records == null ? null : records.get(0);
	}

	@Override
	public Result update(Contract contract) {
		return contractDao.update(contract,"code","name","description","projectId","principalId") ? Result.success() : Result.fail("更新合同失败!");
	}

	@Override
	public List<Contract> listByProjectId(int id) {
		return contractDao.search(Cnd.where("projectId", "=", id));
	}
}